﻿using System;
using System.Collections.Generic;
using Soveryn.Commerce.BaseClasses;
using Soveryn.Commerce.Shared;
using System.Data;
using System.Web.UI.WebControls;
using Soveryn.Commerce.API;

namespace Soveryn.Commerce.Doodads
{

    public partial class BlogPreview : DoodadBaseClass
    {

        new protected void Page_Load(object sender, EventArgs e)
        {

            base.Page_Load(sender, e);

            if (IsPostBack)
                return;

            HTMLLiteral.Text = Properties.DoodadInstanceHTML;

            if (ParentPage.EditMode && ParentPage.EmployeeLoggedIn)
            {
                HTMLPanel.CssClass = "editable";
                HTMLPanel.Attributes.Add("data-id", Properties.ElementID);
            }

            int PostsToShow = Convert.ToInt32(GetPropertyValue("PostsToShow"));

            if(!String.IsNullOrEmpty(GetPropertyValue("BlogCategoryID", "")))
                BlogPostRepeater.DataSource = WebsiteData.BlogPostListTopByCategory(PostsToShow, Convert.ToInt32(GetPropertyValue("BlogCategoryID")));
            else
                BlogPostRepeater.DataSource = WebsiteData.BlogPostListTop(PostsToShow);

            BlogPostRepeater.DataBind();

        }

        protected void BlogPostRepeater_ItemDataBound(Object sender, RepeaterItemEventArgs e)
        {

            DataRowView drv = (DataRowView)e.Item.DataItem;
            BlogPostProperties post = BlogPostProperties.Create(drv.Row);

            Image BlogImage = (Image)e.Item.FindControl("BlogImage");
            HyperLink TitleHyperLink = (HyperLink)e.Item.FindControl("TitleHyperLink");
            Label SummaryLabel = (Label)e.Item.FindControl("SummaryLabel");
            HyperLink ReadMoreHyperLink = (HyperLink)e.Item.FindControl("ReadMoreHyperLink");

            BlogImage.ImageUrl = "/SiteImagesCache/small-" + post.BlogPostImage;

            TitleHyperLink.Text = post.BlogPostTitle;
            TitleHyperLink.NavigateUrl = BlogPostProperties.GetURL(Page, post);

            ReadMoreHyperLink.NavigateUrl = TitleHyperLink.NavigateUrl;

            SummaryLabel.Text = post.BlogPostSummary.Substring(0, Math.Min(post.BlogPostSummary.Length, 80));
            if (SummaryLabel.Text.LastIndexOf(" ") != -1)
            {
                SummaryLabel.Text = SummaryLabel.Text.Substring(0, SummaryLabel.Text.LastIndexOf(" "));
            }

        }

    }
}
